const { app, BrowserWindow, screen, ipcMain, shell } = require('electron')
const path = require('path')
const fs = require('fs')
const os = require('os')
const multiparty = require('multiparty')

const createWindow = () => {
    ipcMain.on("open_youdao", (event, arg) => {
        if (arg.word) CreatYoudaoWindow(arg.word)
    })
    ipcMain.on("open_renjiao", (event, arg) => {
        let renjiao = new BrowserWindow({
            width: 1024,
            height: 768,
            title: "有道翻译",
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
                preload: path.join(__dirname, 'tools/renjiao.js')
            }
        })
        //youdao.webContents.openDevTools()
        renjiao.setMenu(null)
        renjiao.loadURL(arg)
    })
    ipcMain.on("on_link", (event, arg) => {
        // 默认浏览器打开
        shell.openExternal(arg)
    })

    const win = new BrowserWindow({
        width: 1125,
        height: 680,
        //transparent: true,
        //frame: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webviewTag: true
        }

    })

    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
    } else {
        win.loadFile("dist/index.html")
    }
    win.on('close', () => {
        app.quit()
    })
    win.webContents.openDevTools()
    // 全屏
    //win.setFullScreen(true)

    // 隐藏menu
    win.setMenu(null)
    // 置顶
    //win.setAlwaysOnTop(true)
    // 点击穿透
    //setTimeout(() => {
    //    win.setIgnoreMouseEvents(true)
    //}, 10000)
    setTimeout(() => {
        //let wind = new BrowserWindow({
        //    width: 1024,
        //    height: 768,
        //})
        //wind.setSkipTaskbar(true)

    }, 5000)

    let on_msg = new BrowserWindow({
        width: 1000,
        height: 1000,
        transparent: true,
        frame: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    })
    // 窗口贴屏幕最上方，水平居中
    // 获取屏幕宽高
    let { width, height } = screen.getPrimaryDisplay().workAreaSize
    on_msg.setPosition(width / 2 - 500, 0)
    // 鼠标穿透
    on_msg.setIgnoreMouseEvents(true)
    on_msg.setAlwaysOnTop(true)
    on_msg.setSkipTaskbar(true)
    on_msg.setMenu(null)
    on_msg.webContents.openDevTools()
    if (process.env.VITE_DEV_SERVER_URL) {
        on_msg.loadURL(process.env.VITE_DEV_SERVER_URL + "#/on-msg")
    } else {
        on_msg.loadFile("dist/index.html", { hash: "/on-msg" })
    }



    const ctg = new BrowserWindow({
        width: 300,
        height: 1000,
        transparent: true,
        frame: false,

        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        }
    })
    if (process.env.VITE_DEV_SERVER_URL) {
        ctg.loadURL(process.env.VITE_DEV_SERVER_URL + "#/class-table-gui")
    } else {
        ctg.loadFile("dist/index.html", { hash: "/class-table-gui" })
    }
    ctg.setMenu(null)
    ctg.setAlwaysOnTop(true)
    //ctg.webContents.openDevTools()
    // 窗口贴屏幕最右方，竖直居中
    ctg.setSkipTaskbar(true)
    let { width: w, height: h } = screen.getPrimaryDisplay().workAreaSize
    ctg.setPosition(w - 290, h / 2 - 500)
    ctg.setIgnoreMouseEvents(true)




    setInterval(() => {
        // 是否置顶
        let is_top = on_msg.isAlwaysOnTop() && ctg.isAlwaysOnTop()
        if (!is_top) {
            on_msg.setAlwaysOnTop(true)
            ctg.setAlwaysOnTop(true)
        }

    }, 1000)
}

const CreatYoudaoWindow = (word) => {
    let youdao = new BrowserWindow({
        width: 1024,
        height: 768,
        title: "有道翻译",
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            preload: path.join(__dirname, 'tools/youdao.js')
        }
    })
    //youdao.webContents.openDevTools()
    youdao.setMenu(null)
    youdao.loadURL("https://www.youdao.com/result?word=" + word + "&lang=en")
}


app.whenReady().then(() => {
    const http = require('http');
    const express = require('express');
    const cors = require('cors');

    //创建一个应用，注意app其实就是一个函数，类似function(req, res) {}
    let app = express();
    app.use(cors());
    //创建一个http服务器，既然app是一个函数，那这里就可以传入。
    let server = http.createServer(app);
    //注意，websocket的握手是需要依赖http服务的，所以这里要把server传入进去。
    let io = require('socket.io')(server);

    app.get('/api/tools/youdao', function (req, res) {
        // 获取query参数
        console.log(req.query)
        let word = req.query['word']
        fetch("https://dict.youdao.com/suggest?num=5&ver=3.0&doctype=json&cache=false&le=en&q=" + word).then(res => res.json()).then((data) => {
            res.json(data)
        }).catch((err) => {
            res.json({
                code: 500,
                msg: 'fail',
                data: {}
            })
        })
    });

    app.post("/api/file_upload", function (req, res) {
        let form = new multiparty.Form();
        form.uploadDir = path.join(os.homedir(), "jiao-gong-file"); //设置上传目录
        // 重命名为此格式: 2019-08-26 14:53:07.<ext>
        // -----------------------------------------------------------------------------------
        form.parse(req, function (err, fields, file) {
            console.log(file);
            res.send('数据已接收');
        });

    })

    //有新的客户端连接时触发
    io.on('connection', function (socket) {
        console.log("有新客户端连接");
        // 断开
        socket.on('disconnect', function () {
            console.log("客户端断开");
        });
    });

    try {
        server.listen(11451, function () {
            console.log('server is running at port 11451');
            // 在C:/user/<用户名>下创建jiao-gong-file文件夹,如果不存在则创建，如果存在则忽略
            // 获取系统用户名
            let homePath = os.homedir()
            fs.mkdirSync(path.join(homePath, "jiao-gong-file"), { recursive: true })
            createWindow()
        });
    }
    catch (e) {
        // electron 弹出错误
        dialog.showErrorBox("错误", "启动失败，请检查端口是否被占用，请重启电脑后重试")
        app.quit()
    }




})